package com.it.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.bean.User;
import com.it.dto.UserDTO;
import com.it.dto.UserRoleDTO;
import com.it.mapper.UserMapper;
import com.it.page.PageQuery;
import com.it.service.UserService;
import com.it.utils.AppUtils;
import com.it.vo.UserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service("userService")
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public PageInfo<UserVo> page(PageQuery<UserDTO> pageQuery) {
        PageHelper.startPage(pageQuery.getPage(), pageQuery.getPageSize());
        List<UserVo> users = userMapper.selectJoin(pageQuery.getQueryBody());
        return new PageInfo<>(users);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(UserRoleDTO user) {
        if (user.getId() == null) {
            //设置默认密码
            user.setPassword(AppUtils.md5("123456"));
            AppUtils.forSaveAudit(user);
            userMapper.save(user);
        } else {
            AppUtils.forUpdateAudit(user);
            userMapper.updateByPrimaryKeySelective(user);
        }
        //设置角色
        Long id = user.getId();
        List<Long> roleIds = user.getRoleIds();
        userMapper.replaceRoles(id, roleIds);
    }

    @Override
    public List<User> list(User user) {
        user.setDeleted(false);
        return userMapper.select(user);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        user.setDeleted(true);
        AppUtils.forUpdateAudit(user);
        userMapper.updateByPrimaryKeySelective(user);
    }
}
